package org.ats.mail;

import java.io.File;
import java.util.List;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service("AtsMailPreperator")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class AtsMailPreperator{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Autowired
	private MimeMessage mime;
	
	@Autowired
	private MimeMessageHelper helper;

	public MimeMessageHelper getHelper() {
		return helper;
	}

	public void setHelper(MimeMessageHelper helper) {
		this.helper = helper;
	}

	public MimeMessage getMime() {
		return mime;
	}

	public void setMime(MimeMessage mime) {
		this.mime = mime;
	}
	
	public void PrepareMIMEMsg(MailTemplates mailTemp, List<String> mailToList, File attachment){
		MailTemplateProcessing mtp = new MailTemplateProcessor();
		MailContent mc = mtp.ProcessTemplate(mailTemp);
		String[] mailToArray;
		
		try {
			getHelper().setSubject(mc.getSubject());
			getHelper().setFrom(mc.getFrom());
			getHelper().setText(mc.getMailText(), true);
			getHelper().addInline(mc.getInlinePhotoName(), mc.getInlinePhotoFile());
			getHelper().addAttachment(attachment.getName(), attachment);
			if(mailToList.size() == 1){
				getHelper().setTo(mailToList.get(0));
			}else{
				mailToArray = mailToList.toArray(new String[mailToList.size()]);
				getHelper().setTo(mailToArray);
			}
			
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void PrepareMIMEMsg(MailContent mc){
		
		try {
			getHelper().setSubject(mc.getSubject());
			getHelper().setFrom(mc.getFrom());
			getHelper().setText(mc.getMailText(), true);
			getHelper().addInline(mc.getInlinePhotoName(), mc.getInlinePhotoFile());
			getHelper().addAttachment(mc.getAttachment().getName(), mc.getAttachment());
			
			if(mc.getMailToList().size() == 1){
				getHelper().setTo(new InternetAddress(mc.getMailToList().get(0)));
			}else{
				getHelper().setTo(mailValidator(mc.getMailToList()));
			}
			
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException a) {
			a.printStackTrace();
		}
	}
	
	public InternetAddress[] mailValidator(List<String> mailToList) throws AddressException{
		InternetAddress[] iAdrs;
		iAdrs = new InternetAddress[mailToList.size()];
		for(int i=0; i <= mailToList.size(); i++ ){
				iAdrs[i] = new InternetAddress(mailToList.get(i));
				iAdrs[i].validate();
		}
		return iAdrs;
	}

}
